﻿using Microsoft.EntityFrameworkCore;
using MyComp.BulkModule.Entities;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;

namespace MyComp.BulkModule.EntityFrameworkCore.Repositories
{
    public class TableABulkRepository : ITableABulkRepository, ITransientDependency
    {
        private readonly DataBulkDbContext _bulkContext;
        public TableABulkRepository(DataBulkDbContext dbContext)
        {
            _bulkContext = dbContext;
        }
        /// <summary>
        /// 批量插入或更新
        /// </summary>
        /// <param name="importData">数据源</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task UpsertManyAsync(IEnumerable<TableA> importData, CancellationToken cancellationToken = default)
        {
            var ms = importData.Select(t => new { t.Id, t.Code, t.Name, t.Desc });

            await _bulkContext.TableA.UpsertAsync(ms,
                insertExpression:
                    s => new TableA { Id = s.Id, Code = s.Code, Name = s.Name, Desc = s.Desc },
                updateExpression: 
                    (rc1, rc2) => new TableA { Code = rc2.Code, Name = rc2.Name, Desc = rc2.Desc + rc1.Code }
                );
        }
    }
}
